/*
 * Copyright (c) 2023-2299 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.common.listener;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.lam.common.constant.CommonConstant;
import com.lam.common.constant.MallStateConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.NumberUtil;
import com.lam.mall.api.common.order.PreSubmitOrderOrder;
import com.lam.mall.api.service.TransFeeManagerService;
import com.lam.mall.app.param.OrderParam;
import com.lam.mall.app.vo.ShopCartItemVo;
import com.lam.mall.app.vo.ShopCartOrderVo;
import com.lam.mall.common.event.PreSubmitOrderEvent;
import com.lam.mall.entity.ProdSku;
import com.lam.mall.entity.Product;
import com.lam.mall.entity.UserAddr;
import com.lam.mall.service.ProdSkuService;
import com.lam.mall.service.ProductService;
import com.lam.mall.service.UserAddrService;

/**
 * 确认订单信息时的默认操作
 */
@Component("defaultPreSubmitOrderListener")
public class PreSubmitOrderListener {

	@Autowired
    private UserAddrService userAddrService;
	@Autowired
    private TransFeeManagerService transFeeManagerService;
	@Autowired
    private ProductService productService;
	@Autowired
    private ProdSkuService prodSkuService;

    /**
     * 计算订单金额
     */
    @EventListener(PreSubmitOrderEvent.class)
    @Order(PreSubmitOrderOrder.DEFAULT)
    public void defaultConfirmOrderEvent(PreSubmitOrderEvent event) {


        ShopCartOrderVo shopCartOrderVo = event.getShopCartOrderVo();
        OrderParam orderParam = event.getOrderParam();
        String userId = TokenUtils.getLoginUserid();
        // 订单的地址信息
        UserAddr userAddr = userAddrService.getUserAddrCache(orderParam.getAddrId(), userId);
        
        int totalCount = 0;
        BigDecimal total = BigDecimal.ZERO;
        BigDecimal transfee = BigDecimal.ZERO;

        for (ShopCartItemVo shopCartItem : event.getShopCartItems()) {
            // 获取商品信息
            Product prodCache = productService.getSampleProdByIdCache(shopCartItem.getProdId());
            // 获取sku信息
            ProdSku skuCache = prodSkuService.getBySkuIdCache(shopCartItem.getSkuId());
            if (prodCache == null || skuCache == null) {
                throw new BusinessException("购物车包含无法识别的商品");
            }
            if (!NumberUtil.eq(prodCache.getStatus(), MallStateConstant.STATUS_ONLINE) 
            		|| !NumberUtil.eq(skuCache.getStatus(), CommonConstant.STATUS_NORMAL_1)) {
                throw new BusinessException("商品[" + skuCache.getProdName() + "]已下架");
            }

            totalCount = shopCartItem.getProdCount() + totalCount;
            total = NumberUtil.add(shopCartItem.getProductTotalAmount(), total);
            // 用户地址如果为空，则表示该用户从未设置过任何地址相关信息
            if (userAddr != null) {
                // 每个产品的运费相加
                transfee = NumberUtil.add(transfee, transFeeManagerService.calcTransfee(shopCartItem, userAddr));
            }

            shopCartItem.setActualTotal(shopCartItem.getProductTotalAmount());
            shopCartOrderVo.setTotal(total);
            shopCartOrderVo.setShopReduce(BigDecimal.ZERO);
            shopCartOrderVo.setActualTotal(total);
            shopCartOrderVo.setTotalCount(totalCount);
            shopCartOrderVo.setTransfee(transfee);
        }
    }
}
